﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using ServerLibrary.Abstract;
namespace ServerLibrary.Concrete
{
     /// <summary>
    /// Implements configurator with server configurations.
    /// </summary>
    public class Configurator : IConfigurator
    {
        /// <summary>
        /// Singletone instanse.
        /// </summary>
        private static volatile Configurator instance;

        private static object syncRoot = new object();
        
        /// <summary>
        /// Default constructor.
        /// </summary>
        private Configurator()
        {
            Load();
        }

        /// <summary>
        /// Gets configurator instance.
        /// </summary>
        public static Configurator Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Configurator();
                    }
                }

                return instance;
            }
        }

        #region IConfigurator implements
        
        public string IpAddress { get; set; }
        
        public  uint Port { get; set; }
         
        public  ushort MaxUserQuantity { get; set; }
       
        public  List<string> availableFormats { get; set; }

        public string DocumentsRoot { get; set; }
       
        #endregion

        /// <summary>
        /// Loading configurations.
        /// </summary>
        /// <param name="fileName">Path to config file.</param>
        private  void Load()
        {
            availableFormats = new List<string>();
            XmlDocument doc = new XmlDocument();
            doc.Load("Config.xml");
            XmlNode config = doc.SelectSingleNode("Configurations");
            IpAddress = config.SelectSingleNode("IpAddress").InnerText;
            Port = uint.Parse(config.SelectSingleNode("Port").InnerText);
            MaxUserQuantity = ushort.Parse(config.SelectSingleNode("MaxUserQuantity").InnerText);
            DocumentsRoot = config.SelectSingleNode("DocumentsRoot").InnerText;
            XmlNode AvailableFormats = config.SelectSingleNode("AvailableFormats");
            foreach (XmlNode Format in AvailableFormats.ChildNodes)
            {
                availableFormats.Add(Format.InnerText);
            }
        }
    }
}
